package com.rxyb.security.handler;

import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author YJH
 * @version 1.0
 * @description
 * @date 2020/7/7 11:19
 */
public class LoginFailHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 获取登录成功信息
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String context = "";
        if (exception instanceof AccountExpiredException) {
            //账号过期
            context = "账号过期";
        } else if (exception instanceof BadCredentialsException) {
            //密码过期
            context = "密码错误";
        } else if (exception instanceof CredentialsExpiredException) {
            //密码错误
            context = "密码过期";
        } else if (exception instanceof DisabledException) {
            //账号不可用
            context = "账号不可用";
        } else if (exception instanceof LockedException) {
            //账号锁定
            context = "账号锁定";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            //用户不存在
            context = "用户不存在";
        } else {
            //其他错误
            context = "未知错误";
        }
        request.getServletContext().getRequestDispatcher("/login?msg=" + context).forward(request, response);
    }
}
